<template>
  <div class="divBox">
    <el-card class="box-card" shadow="hover">
      <template v-slot:header>
        <div class="container">
          <el-form size="small" label-width="72px">
            <el-row :gutter="24">
              <el-col v-bind="grid">
                <el-form-item label="规格搜索：">
                  <el-input v-model="tableFrom.keyword" placeholder="请输入规格名称" class="search-select" clearable>
                    <template v-slot:append>
                      <el-button icon="el-icon-search" @click="seachList" />
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="acea-row">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addRule">添加商品规格</el-button>
          <el-button v-if="isRule" size="small" @click="addRuleAll">批量增加</el-button>
          <el-button size="small" type="primary" icon="el-icon-close" :disabled="!disabled" @click="delectAll">批量删除规格</el-button>
        </div>
      </template>

      <el-table
        ref="table"
        v-loading="tabLoading"
        :data="tableData.data"
        style="width: 100%;"
        size="mini"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="ruleName" label="规格名称" min-width="150"></el-table-column>
        <el-table-column label="商品规格" min-width="250">
          <template slot-scope="{ row }">
            <span>{{ row.attrName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品属性" min-width="300">
          <template slot-scope="{ row }">
            <div v-for="(item, index) in row.ruleValue" :key="index" v-text="item.attrValue" />
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="onEdit(scope.row)">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" size="small" @click="handleDelete(scope.row.id, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="pagination.total > 0"
        :total="pagination.total"
        :page.sync="pagination.currentPage"
        :limit.sync="pagination.limit"
        :page-sizes="[10, 20, 30, 50]"
        @pagination="pageChange"
      />
    </el-card>
  </div>
</template>

<script>
import { templateListApi, attrDeleteApi, attrCreatApi } from '@/api/store'

export default {
  name: 'ProductAttr',
  data() {
    return {
      grid: {
        xl: 5,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24
      },
      disabled: false,
      tableFrom: {
        keyword: ''
      },
      // 加载
      tabLoading: false,
      // 分页
      pagination: {
        total: 0,
        currentPage: 1,
        limit: 10
      },
      formDynamics: {
        ruleName: '',
        ruleValue: []
      },
      // 表格选中的数据
      selectionList: [],
      // 是否开启批量复制功能
      isRule: false,
      // 所有选中的数据包含跨页数据
      multipleSelectionAll: [],
      // 当前页选中的数据
      multipleSelection: [],
      // 标识列表数据中每一行的唯一键的名称
      idKey: 'id',
      // 表格数据
      tableData: {
        data: []
      }
    }
  },
  mounted() {
    // 获取数据
    this.getList()
  },
  methods: {
    // 搜索
    seachList() {
      this.pagination.currentPage = 1
      this.getList()
    },
    // 删除
    handleDelete(id, index) {
      this.$modalSure().then(() => {
        attrDeleteApi(id).then(res => {
          this.$message.success('删除成功!')
          this.tableData.data.splice(index, 1)
          this.getList()
        })
      }).catch(() => {})
    },
    // 编辑
    onEdit(row) {
      const _this = this
      const rule = JSON.parse(JSON.stringify(row));
      rule.ruleValue.forEach(item => {
        item.attrValue = item.attrValue.split(',');
      });

      this.$modalAttr({
        id: rule.id,
        ruleName: rule.ruleName,
        ruleValue: rule.ruleValue
      }, function() {
        _this.getList();
      })
    },
    // 选择项发生改变时触发
    handleSelectionChange(val) {
      // table组件选中事件
      this.multipleSelection = val
      if (!this.multipleSelection.length) this.disabled = false
      else this.disabled = true
      setTimeout(() => {
        this.changePageCoreRecordData()
      }, 50)
    },
    // 批量删除
    delectAll() {
      if (this.multipleSelection.length === 0) this.$message.warning('请选择商品规格')

      const data = []
      this.multipleSelection.forEach((item) => {
        data.push(item.id)
      });
      const ids = `(${data.join(',')})`
      this.$modalSure().then(res => {
        attrDeleteApi(ids).then(res => {
          this.$message.success('删除成功');
          this.getList();
        });
      });
    },
    // 批量复制
    addRuleAll() {
      if (this.multipleSelection.length === 0) return this.$message.warning('请先至少选择一项');
      this.multipleSelection.forEach((item, index) => {
        attrCreatApi({
          ruleName: item.ruleName,
          ruleValue: JSON.stringify(item.ruleValue)
        }).then(res => {
          this.$message.success('复制成功');
          this.getList();
        });
      });
    },
    // 添加规格
    addRule() {
      const that = this
      this.$modalAttr(Object.assign({}, this.formDynamics), function() {
        that.getList();
      });
    },
    getList() {
      this.$set(this, 'tabLoading', true);
      templateListApi({
        PageNumber: this.pagination.currentPage,
        PageSize: this.pagination.limit,
        Keyword: this.tableFrom.keyword.trim()
      }).then(rule => {
        const list = rule.data;
        this.tableData.data = list;
        list.forEach(item => item.ruleValue = JSON.parse(item.ruleValue));
        this.pagination.total = rule.head.totalCount;
        this.$set(this, 'tabLoading', false);
        this.$nextTick(function() {
          // 调用跨页选中的方法
          this.setSelectRow();
        });
      }).catch(() => {
        this.$set(this.tableData, 'data', []);
        this.$set(this.pagination, 'total', 0);
        this.$set(this, 'tabLoading', false);
      });
    },
    // 点击需要分页的时候触发
    pageChange(data) {
      // 改变页的时候调用
      this.changePageCoreRecordData()
      this.pagination.currentPage = data.page;
      this.getList();
    },
    // 设置选中的方法
    setSelectRow() {
      if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) return
      // 标识当前行的唯一键的名称
      const idKey = this.idKey;
      const selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey])
      });
      this.$refs.table.clearSelection()
      for (var i = 0; i < this.tableData.data.length; i++) {
        if (selectAllIds.indexOf(this.tableData.data[i][idKey]) >= 0) {
          // 设置选中，记住table组件需要使用ref="table"
          this.$refs.table.toggleRowSelection(this.tableData.data[i], true);
        };
      };
    },
    // 记忆选择核心方法
    changePageCoreRecordData() {
      // 标识当前行的唯一键的名称
      const idKey = this.idKey;
      const that = this;
      // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
      if (this.multipleSelectionAll.length <= 0) {
        this.multipleSelectionAll = this.multipleSelection;
        return;
      };
      // 总选择里面的key集合
      const selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey])
      });
      const selectIds = [];
      // 获取当前页选中的id
      this.multipleSelection.forEach(row => {
        selectIds.push(row[idKey])
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.multipleSelectionAll.push(row)
        };
      });
      const noSelectIds = []
      // 得到当前页没有选中的id
      this.tableData.data.forEach(row => {
        if (selectIds.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey])
        };
      });
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.multipleSelectionAll.length; i++) {
            if (that.multipleSelectionAll[i][idKey] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAll.splice(i, 1)
              break
            };
          };
        };
      });
    }
  }
}
</script>

<style lang="scss" scope>
</style>
